import base64
from app.errors import OMSAPIException, OMSAPINotOk

import requests
from requests.auth import HTTPBasicAuth
from flask import current_app as app


def getAuth(username, password):
        serect = username + ":"+password
        bs = str(base64.b64encode(serect.encode("utf-8")), "utf-8")
        return bs


class Client:
    def __init__(self) -> None:
        self.server = app.config['OMS_SERVER']['server']
        self.username = app.config['OMS_SERVER']['username']
        self.password = app.config['OMS_SERVER']['password']

    def ajax(self, uri, params, method='GET', **kwargs,):
        request_args = {
            'url': f'{self.server}{uri}',
            'headers': {
                "Authorization": "Basic {}".format(getAuth(self.username, self.password)),
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.51"
            },
        }
        if method == 'GET':
            request_method = requests.get
            request_args['params'] = params
        elif method == 'POST':
            request_method = requests.post
            request_args['data'] = params
        elif method == 'DELETE':
            request_method = requests.delete
            request_args['data'] = params
        else:
            raise ValueError("'method' error.")

        app.logger.info(f"""Begin Request:
URL   :{request_args.get('url', '')}
params  :{str(params)[:150]}
METHOD:{method}""")
        try:
            resp = request_method(**request_args, **kwargs)
            app.logger.info(f"""END Request:
CODE  :{resp.status_code}
RESP  :{resp.text[:150]}""")
        except Exception as e:
            raise OMSAPIException()
        if resp.ok:
            return resp.json()
        else:
            raise OMSAPINotOk()

    def get(self, uri, params='', **kwargs):
        return self.ajax(uri, params, 'GET', **kwargs)

    def post(self, uri, params, **kwargs):
        return self.ajax(uri, params, 'POST', **kwargs)

    def delete(self, uri, params, **kwargs):
        return self.ajax(uri, params, 'DELETE', **kwargs)
